
<template>
  <base-breadcrumb :title="$route.meta.title" :breadcrumb="!isAudit">
    <!-- 展示区样板实施申请编辑 -->
    <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="editModel != 0 ? rules : {}" id="base-breadcrumb" style="position: relative">
      <a-spin :spinning="loading[0] || loading[1]">
        <!-- 基础信息 -->
        <a-card :bordered="false">
          <title-name title="基础信息"></title-name>
          <custom-form :formList="formList" :isEmit="false" :form="form" :editModel="editModel == 0 ? 'V' : ''" @selectOrg="selectOrg"></custom-form>
        </a-card>
        <!-- 表格 -->
        <a-card :bordered="false" style="margin-bottom: 50px">
          <title-name title="展示区样板实施申请信息"></title-name>
          <b-table ref="table" :isShowCountBar="false" :scroll="{ x: 1600 }" :showPage="false" :columns="columns" :request="loadData">
            <a-button slot="prefix" v-if="editModel != 0" :disabled="form.projectId ? false : true" type="primary" icon="plus" @click="handleAdd">添加计划项</a-button>
            <!-- 样板部位 -->
            <template slot="part" slot-scope="text, record">
              <span v-if="editModel == 0 || record.whetherEdit == 0">{{ text }}</span>
              <BaseInput v-else placeholder="请输入样板部位" v-model="record.part" />
            </template>
            <!-- 样板名称 -->
            <template slot="name" slot-scope="text, record">
              <span v-if="editModel == 0 || record.whetherEdit == 0">{{ text }}</span>
              <BaseInput v-else placeholder="请输入样板名称" v-model="record.name" />
            </template>
            <!-- 劳务单位 -->
            <template slot="subcontractorId" slot-scope="text, record">
              <span v-if="editModel == 0 || record.whetherEdit == 0">{{ record.subcontractor }}</span>
              <template v-else>
                <SelectSubcontractor
                  v-if="record.isFirst"
                  placeholder="请选择劳务单位"
                  :projectId="form.projectId"
                  showSearch
                  :list.sync="subcontractorList"
                  v-model="record.subcontractorId"
                  @select="$set(record, 'monitorId', '')"
                  :extraSubcontractor="{
                    subContractorId: '-1',
                    name: '分包单位未进场'
                  }"
                />
                <a-select v-else v-model="record.subcontractorId" placeholder="请选择劳务单位">
                  <a-select-option v-for="item in subcontractorList" :value="item.subContractorId" :key="item.subContractorId">{{ item.name }}</a-select-option>
                </a-select>
              </template>
            </template>
            <!-- 班组 -->
            <template slot="monitorId" slot-scope="text, record">
              <span v-if="editModel == 0 || record.whetherEdit == 0">{{ record.monitor }}</span>
              <template v-else>
                <!-- v-if="index == 0" -->
                <SelectTeam v-if="record.subcontractorId != '-1'" placeholder="请选择班组" showSearch :form="record" :keyValue="['projectId', 'subcontractorId']" v-model="record.monitorId" />
                <a-select v-else defaultValue="-1" placeholder="请选择班组">
                  <a-select-option value="-1" key="-1">分包单位未进场</a-select-option>
                </a-select>
              </template>
            </template>
            <!-- 计划制作时间 -->
            <template slot="makeDate" slot-scope="text, record">
              <span v-if="editModel == 0 || record.whetherEdit == 0">{{ text }}</span>
              <a-date-picker v-else placeholder="请选择制作时间" valueFormat="YYYY-MM-DD" v-model="record.makeDate" />
            </template>
            <!-- 实施要点 -->
            <template slot="implPoints" slot-scope="text, record">
              <span v-if="editModel == 0 || record.whetherEdit == 0">{{ text }}</span>
              <BaseInput :maxLength="300" v-else placeholder="请输入实施要点" v-model="record.implPoints" />
            </template>
            <template v-if="record.whetherEdit == 1 || editModel != 0" slot="actions" slot-scope="text, record, index">
              <!-- <template v-if="!record.isEdit">
                <a @click="record.isEdit = true">编辑</a>
                <a-divider type="vertical"></a-divider>
              </template> -->
              <!-- 删除 -->
              <a @click="handleDelete(index)">删除</a>
            </template>
          </b-table>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div v-if="!isConsultation" class="btn_box page-btn-right-top">
        <BasePrintButton v-if="editModel == 0 && !isAudit" :beforePrintFn="() => getPritContent('CSCEC8XN-EQ-B30601')" class="button_right" />
        <a-button :disabled="loading[0] || loading[1]" v-if="editModel == 1 && statusCode === '0'" type="danger" class="button_right" @click="handleRemove">删除草稿</a-button>
        <a-button :loading="loading[0]" :disabled="loading[1]" v-if="(editModel == 1 && (statusCode === '0' || statusCode === '3')) || editModel == 2" type="primary" class="button_right" @click="beforoeSubmit(0)">{{
          statusCode === '3' ? '保存' : '保存草稿'
        }}</a-button>
        <a-button :loading="loading[1]" :disabled="loading[0]" v-if="(editModel == 1 && (statusCode === '0' || statusCode === '3')) || editModel == 2" type="primary" class="button_right" @click="beforoeSubmit(1)"
          >提交</a-button
        >
        <a-button v-if="checkVisibleInDetail" type="primary" @click="handleActiveClose">关闭</a-button>
      </div>
    </a-form-model>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { projectShowApply } from '@/api/quality/sample' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import BasePrintButton from '@/components/BasePrintButton' // 打印按钮
import SelectSubcontractor from '@/components/Select/SelectSubcontractor' // 分包商
import SelectTeam from '@/components/Select/SelectTeam' // 班组
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目名称
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    BasePrintButton,
    SelectSubcontractor,
    SelectTeam
  },
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: { 0: false, 1: false },
      editModel: 0,
      subcontractorList: [], // 劳务单位模板
      id: '',
      form: {
        applyItems: [],
        viewName: ''
      },
      loadData: () => {
        return Promise.resolve({ code: 200, data: this.form.applyItems, totalSize: this.form.applyItems?.length || 0 })
      },
      statusCode: '', // 审批状态
      rules: {
        branchCompanyId: [{ required: true, message: '请选择分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
        species: [{ required: true, whitespace: true, message: '请输入拟制作的种类和数量 ', trigger: 'change' }],
        part: [{ required: true, whitespace: true, message: '请输入样板部位', trigger: 'change' }],
        name: [{ required: true, whitespace: true, message: '请输入样板名称', trigger: 'change' }],
        makeDate: [{ required: true, message: '请选择计划制作时间', trigger: 'change' }],
        subcontractorId: [{ required: true, message: '请选择劳务单位', trigger: 'change' }],
        monitorId: [{ required: true, message: '请选择班组', trigger: 'change' }],
        implPoints: [{ required: true, whitespace: true, message: '请输入样板实施要点 ', trigger: 'change' }],
        makeReason: [{ required: true, whitespace: true, message: '请输入样板制作原因说明 ', trigger: 'change' }]
      },
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  async mounted() {
    this.$route.meta.title = ['展示区样板实施申请查看', '展示区样板实施申请编辑', '展示区样板实施申请添加'][this.editModel]
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.loading[0] = true
      projectShowApply
        .getDetail({ id: this.id })
        .then((res) => {
          this.loading[0] = false
          if (res.code === 200) {
            // 添加行标识
            let hasFirst = true
            for (let index in res.data.applyItems) {
              let item = res.data.applyItems[index]
              if (hasFirst && item.whetherEdit != 0) {
                item.isFirst = true
                hasFirst = false
              }
              item.key = 'row' + index
              item.projectId = res.data.projectId
            }
            this.form = res.data
            this.form.viewName = this.form.branchCompanyName + '/' + this.form.projectName
            this.statusCode = res.data?.statusCode
            this.$nextTick(() => {
              this.$refs.table?.getData(null, true)
            })
          }
        })
        .catch(() => {
          this.loading[0] = false
        })
    }
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('quality_show_apply')
  },
  computed: {
    // 表头
    columns() {
      let columns = [
        {
          title: '序号',
          width: 80,
          dataIndex: 'number',
          customRender() {
            return arguments[2] + 1
          }
        },
        {
          title: '样板部位',
          dataIndex: 'part',
          width: 220,
          scopedSlots: { customRender: 'part' }
        },
        {
          title: '样板名称',
          dataIndex: 'name',
          width: 220,
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '劳务单位',
          dataIndex: this.editModel == 0 ? 'subcontractor' : 'subcontractorId',
          width: 220,
          scopedSlots: { customRender: 'subcontractorId' }
        },
        {
          title: '班组',
          dataIndex: this.editModel == 0 ? 'monitor' : 'monitorId',
          width: 220,
          scopedSlots: { customRender: 'monitorId' }
        },
        {
          title: '计划制作时间',
          dataIndex: 'makeDate',
          width: 220,
          scopedSlots: { customRender: 'makeDate' }
        },
        {
          title: '实施要点',
          dataIndex: 'implPoints',
          width: 220,
          scopedSlots: { customRender: 'implPoints' }
        }
      ] // 表头
      if (this.editModel == 0) {
        if (!this.businessId) {
          columns.push({
            title: '实际实施时间',
            width: 180,
            dataIndex: 'constructionDate'
          })
        }
      } else {
        columns.push({
          title: '操作',
          dataIndex: 'actions',
          width: 180,
          fixed: 'right',
          align: 'center',
          scopedSlots: { customRender: 'actions' }
        })
      }
      return columns
    },
    formList() {
      return [
        {
          type: "orgTree",
          span: 16,
          keyName: 'projectId',
          label: '所属单位',
          viewName: 'viewName',
          isAutoSelectFirst: true,
          isNeedAuth:true,
          checkStrictly: true,
          isNoBorder: this.editModel == '0'
        },
        // {
        //   type: SelectSubCompany,
        //   span: 8,
        //   keyName: 'branchCompanyId',
        //   label: '分公司名称',
        //   disabled: this.disabled,
        //   viewName: 'branchCompanyName',
        //   attrs: {
        //     autoSelected: this.editModel == 2
        //   },
        //   change() {
        //     console.log(arguments)
        //   }
        // },
        // {
        //   type: SelectProject,
        //   span: 8,
        //   keyName: 'projectId',
        //   label: '项目名称',
        //   viewName: 'projectName',
        //   attrs: {
        //     autoSelected: this.editModel == 2,
        //     keyValue: 'branchCompanyId',
        //     isClear: this.editModel == 2,
        //     isEdit: this.editModel != 2,
        //     form: this.form
        //   }
        // },
        {
          keyName: 'species',
          type: 'a-input',
          label: '拟制作的样板种类及数量'
        },
        {
          keyName: 'makeReason',
          type: 'BaseTextarea',
          label: '样板制作原因说明',
          span: 24
          // attrs: {
          //   type: 'textarea',
          // },
        }
      ]
    }
  },
  methods: {
    selectOrg(val) {
      this.form.branchCompanyId = val[val.length - 2].orgId
    },
    /**
     * 新增计划项
     */
    handleAdd() {
      let obj = {
        key: `row${this.form.applyItems.length + 1}`,
        isEdit: true,
        projectId: this.form.projectId
      }
      if ((this.form.applyItems.length > 0 && !this.form.applyItems[this.form.applyItems.length - 1].isFirst) || this.form.applyItems.length === 0) {
        obj.isFirst = true
      }
      this.form.applyItems.push(obj)
    },
    /**
     * 删除计划项
     */
    handleDelete(index) {
      this.$confirm({
        title: '温馨提示',
        content: '确定删除计划项？',
        onOk: () => {
          this.form.applyItems.splice(index, 1)
        }
      })
    },
    /**
     * 删除草稿
     */
    handleRemove() {
      this.$confirm({
        title: '温馨提示',
        content: '确定删除草稿？',
        onOk: () => {
          return projectShowApply.remove({ id: this.id }).then((res) => {
            this.$message.success('删除成功！')
            // 关闭当前页
            this.$multiTab.close()
          })
          // .catch((res) => {
          //   this.$message.warning('删除失败！')
          // })
        }
      })
    },
    /**
     * 提交表单之前
     */
    beforoeSubmit(statusCode) {
      // 保存草稿
      if (statusCode === 0) {
        this.handleSubmit(statusCode)
      } else {
        // 提交
        this.$refs.ruleForm.validate((e) => {
          if (e) {
            this.$confirm({
              title: '温馨提示',
              content: '确定提交，提交过后不可撤回？',
              onOk: () => {
                return this.handleSubmit(statusCode)
              }
            })
          } else {
            this.$message.warning("数据填写不完整，不能提交")
          }
        })
      }
    },
    /**
     * 提交表单
     */
    handleSubmit(statusCode) {
      let that = this
      this.setProcessConfig = null;
      let name = ['update', 'create'][that.editModel - 1] // 根据操作切换url地址
      // 校验表单
      if (that.form.applyItems.length > 0) {
        for (let index in that.form.applyItems) {
          let item = that.form.applyItems[index] // 行数据源
          // 若分包商未进场，则设置班组也未进场
          if (item.subcontractorId === '-1') {
            // item.subcontractor = '分包单位未进场'
            // item.monitor = '分包单位未进场'
            item.monitorId = '-1'
          }
          let keys = {
            part: '样板部位',
            name: '样板名称',
            subcontractorId: '劳务单位',
            monitorId: '班组',
            makeDate: '计划制作时间',
            implPoints: '实施要点'
          } // 需要校验的对象
          for (let i in keys) {
            // 存在于校验对象，且表单值为空或不存在时提示
            if (!Object.keys(item).includes(i) || (Object.keys(item).includes(i) && !item[i])) {
              that.$message.warning(`序号${Number(index) + 1}的${keys[i]}不能为空！`)
              return
            }
          }
        }
      } else {
        that.$message.warning('计划项不能为空')
        return
      }
      // 提交表单
      that.loading[statusCode] = true
      let form = that.$clone(that.form)
      form.statusCode = that.statusCode == 3 && statusCode == 0 ? that.statusCode : statusCode
      return projectShowApply[name](form)
        .then((res) => {
          if (res.code === 200 || res.data.code === 200) {
            that.loading[statusCode] = false
            that.$message.success(['保存', '提交'][statusCode] + '成功！')
            if (statusCode * 1 === 1 ) {
              //提交时，返回id
              that.businessId = res.data.id;
              that.loading[statusCode] = false
              that.setProcessConfig = that.processConfig;
              return
            }else{
              that.$multiTab.close()
            }
          }
        })
        .catch((res) => {
          that.$message.error(res?.data?.message || ['保存', '提交'][statusCode] + '失败！')
          that.loading[statusCode] = false
        })
    },
  }
}
</script>

<style lang="less" scoped>
/deep/ .ant-form-item {
  .ant-form-item-label {
    height: 28px;
    width: 200px;
    line-height: 22px;
    padding: 6px 4px 0 0;
    text-align: right;
    white-space: pre-wrap;
    overflow: visible;
  }
  .ant-form-item-control-wrapper {
    width: calc(100% - 200px);
  }
}
/deep/.text_name{
  word-wrap: break-word;
}
</style>
